package com.wanghlme.bookstore.controller.common;

import com.wanghlme.bookstore.bean.VerifyCode;
import com.wanghlme.bookstore.util.common.IVerifyCodeGenerator;
import com.wanghlme.bookstore.util.common.impl.VerifyCodeImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Slf4j
@Controller
public class CommonController {

    @RequestMapping("/")
    public String toMainPage() {
        return "admin/main";
    }

    @RequestMapping("/welcome")
    public String toWelcomePage() {
        return "admin/welcome";
    }

    @RequestMapping("/common/getVerifyCode")
    public void getVerifyCode(HttpServletRequest request, HttpServletResponse response) {
        IVerifyCodeGenerator iVerifyCodeGenerator = new VerifyCodeImpl();
        try {
            VerifyCode verifyCode = iVerifyCodeGenerator.getVerifyCode(100, 30);
            String code = verifyCode.getCode();
            log.debug("当前验证码为：{}", code);
            /* 将 VerifyCode 绑定 session */
            request.getSession().setAttribute("VerifyCode", code);
            /* 设置响应内容类型 */
            response.setContentType("image/jpeg");
            response.getOutputStream().write(verifyCode.getImgBytes());
            response.getOutputStream().flush();
        } catch (IOException e) {
            log.error(e.toString());
            e.printStackTrace();
        }
    }
}
